package com.moyu.crowdsource.controller;

import com.moyu.crowdsource.entity.CommodityImage;
import com.moyu.crowdsource.service.OSSService;
import com.moyu.crowdsource.util.Msg;
import com.moyu.crowdsource.util.MyUUID;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.tomcat.util.http.fileupload.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;

@Api(value="OSScontroller",tags={"OSS文件管理"})
@RestController
@RequestMapping("${api.base}/oss")
public class OSSController {

    @Autowired
    OSSService ossService;

    @ApiOperation("文件上传")
    @PostMapping("/upload")
    public Msg handleFormUpload(MultipartFile multfile, CommodityImage commodityImage){
        if (!multfile.isEmpty()){
            try{
                // 获取文件名
                String fileName = multfile.getOriginalFilename();
                // 获取文件后缀
                String prefix=fileName.substring(fileName.lastIndexOf("."));
                // 用uuid作为文件名，防止生成的临时文件重复
                final File excelFile = File.createTempFile(MyUUID.getUUID32(), prefix);
                // MultipartFile to File
                multfile.transferTo(excelFile);
                ossService.uploadFiled(excelFile,excelFile.getName(),commodityImage);
                deleteFile(excelFile);
                return Msg.success().add("info","文件上传成功");
            }catch (Exception e){
                return Msg.fail().add("转换文件失败",e);
            }


        }
        return Msg.fail().add("info","文件为空");
    }




    @ApiOperation("获取授权图片URL")
    @GetMapping("/geturl")
    public Msg getImageUrl(String imageName){

        return Msg.success().add("url", ossService.getImageUrl(imageName));
    }

    @ApiOperation("测试")
    @GetMapping("/test")
    public Msg test(){
        return Msg.success().add("info",ossService.getTest());
    }

    private void deleteFile(File... files) {
        for (File file : files) {
            if (file.exists()) {
                file.delete();
            }
        }
    }

}
